
<template>
  <div class="app-container">
    <search-header
      v-show="boo.showSearch"
      :select-prop="selectProp"
      @search-action="searchAction"
    ></search-header>

    <div class="app-permission-container flex-between mb8">
      <span class="page-list-title">代理列表</span>
      <div class="action-content">
        <el-button type="primary" size="mini" @click="showDialog('store', 'add')"
        v-hasPermi="['admin:acddShop:add']">新增</el-button>
      </div>
    </div>
    <div class="app-table-container">
      <el-table v-loading="boo.loading" :data="list" border>
        <el-table-column
          label="代理商名称"
          align="center"
          key="agentName"
          prop="agentName"
          :show-overflow-tooltip="true" />
        <el-table-column
          label="负责人"
          align="center"
          key="head"
          prop="head"
          :show-overflow-tooltip="true" />
        <el-table-column
          label="联系电话"
          align="center"
          key="headPhone"
          prop="headPhone"
          :show-overflow-tooltip="true" /> 
        <el-table-column
          label="登录账号"
          align="center"
          key="account"
          prop="account"
          :show-overflow-tooltip="true"/>
        <el-table-column
          label="收益分成"
          align="center"
          key="serviceChargeDivide"
          prop="serviceChargeDivide"/>
        <el-table-column
          label="商户数"
          align="center"
          key="shopNumber"
          prop="shopNumber"
          :show-overflow-tooltip="true"/>
        <el-table-column
          label="上月笔数"
          align="center"
          key="lastMonthOrderNumber"
          prop="lastMonthOrderNumber" />
        <el-table-column
          label="上月收益"
          align="center"
          key="lastMonthMoney"
          prop="lastMonthMoney"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="状态"
          align="center"
          key="cooperationStatus"
          prop="cooperationStatus"
          :show-overflow-tooltip="true">
          <template slot-scope="{row}">
            <el-tag :type="row['cooperationStatus'] == 1 ? 'danger' : 'success'">
              {{ row['cooperationStatus'] | numToStr(dictsList, 'cooperationStatus') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="120"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{row}">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit" v-hasPermi="['admin:acddShop:edit']"
              @click="showDialog('store', 'edit', row)" 
              :loading="row.isEdit"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text" v-hasPermi="['admin:acddShop:pause']"
              icon="el-icon-video-pause"
              :loading="row.isControl"
              @click="controlTypeRow(row)"
              >
              {{ row.cooperationStatus ? '启用' : '停用' }}
              </el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete" v-hasPermi="['admin:acddShop:delete']"
              @click="deleteRow(row)" 
              :loading="row.isDelete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="other.total > 0"
        :total="other.total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    
    <dialog-normal
      ref="dialog-store"
      :dialog-prop="{
          title: dialogStore.title,
          height: '55vh',
          width: '60%',
          submit: '确定',
          close: '取消'
      }"
      @normal-submit="submitDialog('store', dialogStore.currentItem)"
      >
      <template #dialog-content v-if="$refs[`dialog-store`] && $refs[`dialog-store`].showDialog">
        <el-form
          class="form-content"
          ref="store-form" label-position="left"
          :model="dialogStore.currentItem"
          label-width="120px">
          <div class="form-title">基础信息</div> 
          <el-form-item class="form-content-item"
              label="代理商名称：" prop="agentName"
              :rules="{ required: true, message: `代理商名称不能为空`, trigger: 'blur'}">
              <div class="form-val flex-normal">
                <el-input v-model="dialogStore.currentItem['agentName']"></el-input>
              </div>
          </el-form-item>
          <el-form-item class="form-content-item"
              label="负责人：" prop="head"
              :rules="{ required: true, message: `负责人不能为空`, trigger: 'blur'}">
            <div class="form-val flex-normal">
              <el-input v-model="dialogStore.currentItem['head']"></el-input>
            </div>
          </el-form-item>
          <el-form-item class="form-content-item"
              label="负责电话：" prop="headPhone"
              :rules="{ required: true, message: `负责电话不能为空`, trigger: 'blur'}">
            <div class="form-val flex-normal">
              <el-input v-model="dialogStore.currentItem['headPhone']"></el-input>
            </div>
          </el-form-item>
          <el-form-item class="form-content-item"
              label="登录账号：" prop="account"
              :rules="[
                { required: true, message: `登录账号不能为空`, trigger: 'blur'},
                { validator: validatePhoneNum, trigger: 'blur'}
              ]">
            <div class="form-val flex-normal">
              <el-input v-model="dialogStore.currentItem['account']"></el-input>
            </div>
          </el-form-item>
          <el-form-item class="form-content-item"
              label="密码：" prop="password"
              :rules="{ required: true, message: `密码不能为空`, trigger: 'blur'}">
            <div class="form-val flex-normal">
              <el-input v-model="dialogStore.currentItem['password']" type="password"></el-input>
            </div>
            <el-button :loading="boo.randomPassword" @click="randomPassword" class="code-btn-unit" type="text">生成随机密码</el-button>
          </el-form-item>                   
          <el-form-item class="form-content-item"
              label="开户分成：" prop="openAccountDivide"
              :rules="[
                { required: true, message: `开户分成不能为空`, trigger: 'input',},
                { validator: validateMoney, trigger: 'blur'}
              ]">
              <div class="form-val flex-normal">
                <el-input v-model="dialogStore.currentItem['openAccountDivide']" placeholder="请输入开户分成"></el-input>
              </div>
              <span class="code-desc-unit">%</span>
          </el-form-item>                   
          <el-form-item class="form-content-item"
              label="服务费分成：" prop="serviceChargeDivide"
              :rules="[
                { required: true, message: `服务费分成不能为空`, trigger: 'input',},
                { validator: validateMoney, trigger: 'blur'}
              ]">
              <div class="form-val flex-normal">
                <el-input v-model="dialogStore.currentItem['serviceChargeDivide']" placeholder="请输入服务费分成"></el-input>
              </div>
              <span class="code-desc-unit">%</span>
          </el-form-item>
          
          <el-form-item class="form-content-item"
              label="合作状态：" prop="cooperationStatus"
              :rules="{ required: true, message: `合作状态不能为空`, trigger: 'change'}">
            <div class="form-val no-border flex-normal">
              <el-radio-group v-model="dialogStore.currentItem.cooperationStatus">
                <el-radio v-for="radio in getDictItem('status')" :key="radio.dictValue" :label="radio.dictValue">{{radio.dictLabel}}</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
        </el-form>
      </template>
    </dialog-normal>
  </div>
</template>

<script>

import {
    randomPassword
  } from "@/api/userManage/admin-shop.js";
import {
  getAgentList, addAgent, editAgent, deleteAgent, getAgentDetail, controlAgent
} from "@/api/userManage/admin-agent.js";
import {isDecimal, isPhoneNum} from '@/utils/tools.js'
export default {
  name: "List",
  components: {
    "search-header": () => import("@/rhComponents/searchHeader/index"),
    "dialog-normal": () => import("@/rhComponents/dialog/normal-dialog"),
  },
  filters: {
    numToStr(num, list, type){
      let index = list.findIndex(item => item.name == type)
      if(index == -1) return '未定义参数'
      let idx = list[index].child.findIndex(i => i.dictValue == num)
      if(idx == -1) return '---'
      return list[index].child[idx].dictLabel
    }
  },
  data() {
    return {
      selectProp: JSON.parse(JSON.stringify(this.$getSearchHeader(this))),
      boo: {
        loading: false, // 遮罩层
        multiple: true, // 非多个禁用
        showSearch: true, // 显示搜索条件
        randomPassword: false,
      },
      other: {
        ids: [], // 选中数组
        total: 0, //总条数
      },
      dictsList: [
        { label: "合同状态", name: "cooperationStatus", deptType: "status", child: [] },
      ],
      // 地块列表
      list: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      dialogStore: {
        title: '新建商家',
        currentItem: {}
      },
    };
  },
  mounted(){
    let _self = this
    _self.initGetDicts().then(res => {
      _self.getList()
    })    
  },
  methods: {    
  async randomPassword(){
      let _self = this
      _self.boo.randomPassword = true
      await randomPassword().then(res => {
        _self.$set(_self.dialogStore.currentItem, 'password', res.msg)
      })
      _self.boo.randomPassword = false
    },
    getDictItem(name){
      let item = this.dictsList.find(i => i.deptType == name)
      return item.child
    },
    validateMoney: (rule, value, callback) => {
      if (!isDecimal(`${value}`)) {
        callback(new Error('请输入正确的金额'));
      } else {
        callback();
      }
    },
    validatePhoneNum: (rule, value, callback) => {
      if (!isPhoneNum(`${value}`)) {
        callback(new Error('请输入正确手机号'));
      } else {
        callback();
      }
    },
    // 搜索条件查询
    searchAction(prop) {
      this.queryParams = Object.assign(this.queryParams, prop["params"]);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询用户列表 */
    getList() {
      this.boo.loading = true;
      getAgentList(this.queryParams)
        .then((response) => {
          response.rows.forEach(item => {
            item.cooperationStatus = `${item.cooperationStatus}`
          })
          this.list = response.rows;
          this.other.total = response.total;
          this.boo.loading = false;
        })
        .catch(() => {});
    },
    controlTypeRow(row){
      let _self = this
      row.isControl = true
      _self.$set(row, 'isControl', true)
      controlAgent({id: row.id, cooperationStatus: row.cooperationStatus ? '0' : '1'}).then(res => {
        _self.getList()
        _self.$message.success('操作成功')
      }).catch(() => {
        _self.$set(row, 'isControl', false)
      })
    },
    /** 删除按钮操作 */
    deleteRow(row) {
      this.$modal
        .confirm('是否确认删除？')
        .then(function () {
          return deleteAgent(row.id);
        })
        .then(() => {
          this.queryParams.pageNum = 1
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 事件集合 -- 转发
    actionsMaps(ref, acion, row){
      let _self = this
      let actionsMap = () => {
        return new Map([
          [{ref: 'store', acion: 'add:show'}, ()=>{
            _self.dialogStore.title = '添加代理商'
            _self.dialogStore.currentItem = {
              cooperationStatus: '0'
            }
            _self.$nextTick(() => {
              _self.$refs[`dialog-${ref}`].showDialog = true
            })
          }],
          [{ref: 'store', acion: 'edit:show'}, ()=>{
            _self.dialogStore.title = '编辑代理商'
            _self.$set(row, 'isEdit', true)
            getAgentDetail(row.id).then(res => {
              res.data.cooperationStatus = `${res.data.cooperationStatus}`
              _self.dialogStore.currentItem = res.data
              _self.$nextTick(() => {
                _self.$refs[`dialog-${ref}`].showDialog = true
              })
            }).finally(() => _self.$set(row, 'isEdit', false))
          }],
        [{ref: 'store', acion: 'submit'}, ()=>{
          let params = JSON.parse(JSON.stringify(row))
          let success = (res, msg) => {
            _self.$message.success(msg)
            _self.getList()
            _self.$nextTick(() => {
              _self.$refs[`dialog-${ref}`].showDialog = false
            })
          }
          if(params.id){
            editAgent(params).then(res => {
              success(res, '修改成功')
            }).finally(() => {
              _self.$refs[`dialog-${ref}`].loading = false;
            })
          }else {
            addAgent(params).then(res => {
              _self.queryParams.pageNum = 1
              success(res, '添加成功')
            }).finally(() => {
              _self.$refs[`dialog-${ref}`].loading = false;
            })
          } 
        }]
        ])
      }
      let actions = [...actionsMap()].filter(([key,value])=>(key.ref == ref && key.acion == acion))
      actions.forEach(([key,value])=>value.call(this))
    },
    showDialog(ref, type, row) {
      let _self = this;
      if (_self.$refs[`${ref}-form`]) {
        this.resetForm(`${ref}-form`);
      }
      _self.$nextTick(() => {
        _self.actionsMaps(ref, `${type}:show`, row)
      })
    },
    submitDialog(ref, row) {
      let _self = this;
      if(this.$refs[`${ref}-form`]){
        this.$refs[`${ref}-form`].validate((valid) => {
          if (valid) {
            _self.$refs[`dialog-${ref}`].loading = true
            _self.actionsMaps(ref, `submit`, row)
          } else {
            _self.$refs[`dialog-${ref}`].loading = false;
            return false;
          }
        });
      }else{
        _self.$refs[`dialog-${ref}`].loading = true
        _self.actionsMaps(ref, `submit`, row)
      }
    },
  }
};
</script>
<style scoped lang="scss">
.form-content{
  .form-content-item{
    position: relative;
    .code-btn-unit, .code-desc-unit, .code-success-unit{
      position: absolute;
      left: vw(400);
      top: 50%;
      transform: translateY(-50%);
      font-size: vh(13);
    }
    .code-btn-unit{
      color: #0003AA;
      cursor: pointer;
    }
    .code-success-unit{
      color: #0003AA;
    }
  }
  .form-title{
    margin-bottom: vh(20);
    line-height: vh(34);
    font-size: vh(13);
    color: #0003AA;
  }
  .form-val {
    width: vw(360);
    flex-wrap: nowrap;
    &.no-border{
      border: none;
    }
  }
}
</style>